package org.xq.softcup.mq.remoting.invoker.router.impl;

import org.xq.softcup.mq.remoting.invoker.router.XQRpcLoadBalance;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentHashMap;

public class XQRpcLoadBalanceLRUStrategy extends XQRpcLoadBalance
{
    private ConcurrentHashMap<String, LinkedHashMap<String, String>> jobLRUMap = new ConcurrentHashMap();
    private long CACHE_VALID_TIME = 0L;

    public String doRoute(String serviceKey, TreeSet<String> addressSet)
    {
        if (System.currentTimeMillis() > this.CACHE_VALID_TIME)
        {
            this.jobLRUMap.clear();
            this.CACHE_VALID_TIME = (System.currentTimeMillis() + 86400000L);
        }
        LinkedHashMap<String, String> lruItem = (LinkedHashMap)this.jobLRUMap.get(serviceKey);
        if (lruItem == null)
        {
            lruItem = new LinkedHashMap(16, 0.75F, true);
            this.jobLRUMap.putIfAbsent(serviceKey, lruItem);
        }
        for (String address : addressSet) {
            if (!lruItem.containsKey(address)) {
                lruItem.put(address, address);
            }
        }
        String eldestKey = (String)((Map.Entry)lruItem.entrySet().iterator().next()).getKey();
        String eldestValue = (String)lruItem.get(eldestKey);
        return eldestValue;
    }

    public String route(String serviceKey, TreeSet<String> addressSet)
    {
        String finalAddress = doRoute(serviceKey, addressSet);
        return finalAddress;
    }
}

